<?php

namespace App\Http\Controllers\Api\V1;

use App\B2BProject\Custom\AuthorizationRequest;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class MyAuthorizationRequestController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $authorizationRequests = \Auth::user()->purchaserAuthorizationRequests();

        if (in_array($status = $request->query('status') - 1, [0, 1, 2, 3])) {
            $authorizationRequests->where('status', $status);
        }

        if ($provider = $request->query('provider')) {
            $authorizationRequests->whereHas('provider.information', function ($query) use ($provider) {
                $query->where('company', 'like', "%$provider%");
            });
        }

        $authorizationRequests = $authorizationRequests->orderBy('created_at', 'desc')->get();

        $data = [];

        foreach ($authorizationRequests as $authorizationRequest) {
            $data[] = [
                'id'        => $authorizationRequest->id,
                'provider'  => $authorizationRequest->provider->information->company,
                'time'      => date('Y-m-d H:i:s', strtotime($authorizationRequest->created_at)),
                'timestamp' => strtotime($authorizationRequest->created_at),
                'status'    => $authorizationRequest->status + 1,
            ];
        }

        return success_return(['list' => $data]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int                      $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // 当前的修改只可能是取消功能
        $authorizationRequest = AuthorizationRequest::findOrFail($id);

        $authorizationRequest->status = 3;

        $authorizationRequest->save();

        return success_return(null);
    }
}
